package org.rendao.biz.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.rendao.biz.data.FirstIndexDO;
import org.rendao.biz.model.FirstIndex;
import org.rendao.biz.service.FirstIndexService;
import org.rendao.constant.ConstantDefinition;
import org.rendao.dao.IGenericDao;
import org.rendao.exception.TBFError;
import org.rendao.exception.TBFException;
import org.rendao.utils.AssembleUtils;
import org.rendao.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

public class FirstIndexServiceImpl implements FirstIndexService {

	private IGenericDao<FirstIndexDO> dao;

	public void setDao(IGenericDao<FirstIndexDO> daoToSet) {
		dao = daoToSet;
		dao.setClazz(FirstIndexDO.class);
	}

	@Autowired
	private NamedParameterJdbcTemplate jdbcTemplate;
	
	public void setJdbcTemplate(NamedParameterJdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}
	
	@Override
	public FirstIndex getById(String id) {
		FirstIndexDO firstIndexDO = dao.getById(id);
		return AssembleUtils.shadowCopy(firstIndexDO, FirstIndex.class);
	}

	@Override
	public FirstIndex saveOrUpdate(FirstIndex firstIndex) {
		FirstIndexDO firstIndexDO = AssembleUtils.shadowCopy(firstIndex, FirstIndexDO.class);
		FirstIndexDO resultDO = null;
		if(StringUtils.isNullOrEmpty(firstIndex.getId())) {
			resultDO = dao.save(firstIndexDO);
		}
		else {
			resultDO = dao.update(firstIndexDO);
		}
		return AssembleUtils.shadowCopy(resultDO, FirstIndex.class);
	}

	@Override
	public List<FirstIndex> getAll() {
		List<FirstIndexDO> list = dao.getAllAvailable();
		return AssembleUtils.shadowCopyList(list, FirstIndex.class);
	}

	@Override
	public int deleteById(String id) {
		String sql = "select count(*) from second_index where first_index_id = :first_index_id" +
				" and is_deleted = :is_deleted";
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("first_index_id", id);
		params.put("is_deleted", ConstantDefinition.IS_DELETED_FALSE);
		int count = jdbcTemplate.queryForInt(sql, params);
		if(count > 0) {
			throw new TBFException(TBFError.ASSOCIATION_DELETE_DENY);
		}
		return dao.softDelete(id);
	}

	
}
